<?php

namespace App\Repository\Commission;

use App\Jobs\Subpackage;
use App\Libs\PhpOffice\Excel;
use App\Models\Orders\OrderCommissionCountModel;
use App\Models\Orders\OrderCommissionDataModel as model_data;
use App\Models\Orders\OrderCommissionMiddModel;
use App\Models\Orders\OrderCommissionModel as model;
use App\Models\Orders\OrderMiddModel;
use App\Repository\BaseRepository;
use App\Repository\Orders\OrderCommissionFileRepository;
use App\Repository\Orders\OrdersRepository;
use Illuminate\Support\Facades\DB;

class CommissionFileRepository extends BaseRepository
{
    private $model;
    private $productModel;
    private $dataModel;
    private $isType;
    private $orderModel;

    public function __construct()
    {
        $this->model = new model;  // 佣金上传的文件
        $this->productModel = new OrderCommissionMiddModel;
        $this->dataModel = new model_data();
        $this->orderModel = new OrdersRepository();
        parent::__construct();
    }

    // 佣金逻辑处理
    public function getAllCommissionData($id)
    {
        if (empty($id)) {
            return $this->returnMsg(1, '传递参数不能为空');
        }
        $model = new OrderCommissionFileRepository();
        $resMore = $model->getOne(['id' => $id, 'is_run' => 0]);
        // $this->log->info('文件参数:' . $id . '查询结果' . json_encode($resMore));
        if (!($resMore)) {
            return $this->returnMsg(2, '未查询到数据');
        }
        $this->isType = $resMore->type;
        return $this->readLongFile($resMore->upload_rout, $resMore->type, $resMore->time, $resMore->shop_id, $id);
    }

    public function readLongFile($path, $type, $time, $shop_id, $id = '', $fiel_name = '')
    {
        $path = public_path($path);
        // var_dump($path);
        // die();
        if (empty($path) || !file_exists($path)) {
            return $this->returnMsg(100, '文件不存在');
        }
        if (empty($type)) {
            return $this->returnMsg(102, '类型不能为空');
        }
        if (empty($shop_id)) {
            return $this->returnMsg(103, '用户id 不存在');
        }
        $model = new Excel();
        $res = [];
        $count = 0;
        $fielCount = 0;
        $count_amount = 0;
        $data = $model->importFile($path, ['dist_orderno', 'iccid', 'amount', 'three_msg'], function ($data) use ($shop_id, $id, $fiel_name, $type, $time) {
            $data['shop_id'] = $shop_id;
            $data['more_file_id'] = $id;
            $data['dist_name'] = $fiel_name;
            $data['type'] = $type;
            $data['act_time'] = $time;
            return $data;
        });
        // var_dump($data);
        if (!empty($data['data'])) {
            $modelInSert = new OrderCommissionMiddModel();
            foreach (array_chunk($data['data'], 100, true) as $key => $v) {
                $res = $this->oneInsert($modelInSert, $v);
            }
            $count = count($data['data']);
        }
        $update = [
            'is_run' => 1,   // 运行中
            'success_num' => $count,
            'fail_num' => $fielCount,
            'count_amount' => $count_amount,
        ];
        // 加入 中间表 读取到正式表中
        dispatch(new Subpackage($id, 'createCommission', 5))->onQueue('TaskLongFileDispose');
        $model = new OrderCommissionFileRepository();
        return $model->edit(['id' => $id], $update);
    }

    public function oneInsert($model, $data)
    {

        return $model->insert($data);
    }

    // 生成佣金数据
    public function createCommission($field_id)
    {
        if (empty($field_id)) {
            return $this->returnMsg(100, '请传递佣金的编码');
        }
        $where = [
            'is_run' => 0,
            'more_file_id' => $field_id
        ];
        $resData = $this->productModel->where($where)->limit(50)->get();
        // 根据 dist_orderno 和 iccid  查询订单 读取出来 分销商
        //  dist_id  dist_shop dist_name dist_orderno  shop_id  sup_id  sup_name
        // express_num  express_name  status_desc  amount
        // order_date  sett_date time goods_name  goods_code  type  fail_id  phone

        if (!empty($resData)) {
            foreach ($resData as $key => $v) {
                $flag = true;
                $three_msg = ''; // 第三方 失败原因
                $whereOrder = [];
                if (!empty($v->dist_orderno)) {
                    $whereOrder['ordersno'] = $v->dist_orderno;
                }
                if (!empty($v->iccid)) {
                    $whereOrder['iccid'] = $v->iccid;
                }
                if (empty($whereOrder)) {
                    $three_msg = '订单号和入网手机号不能同时为空';
                    $flag = false;
                    // continue;
                }
                if ($flag) {
                    // 查询订单
                    $orderAll = $this->orderModel->getOne($whereOrder);
                    if (!$orderAll) {
                        $flag = false;
                        $three_msg = '未查询到订单';
                    }
                    // 效验
                    if ($flag) {
                        if ($v->is_val == 1) {
                            $whereOrder['type'] = $v->type;
                            $isTrue = $this->model->where($whereOrder)->first();
                            if ($isTrue) {
                                $flag = false;
                                $three_msg = '该单已分发佣金';
                            }
                        }
                    }
                    if ($flag) {
                        $timeSett = date('Y-m-d H:i:s');
                        // 单个的插入
                        $addData = [
                            'amount' => ($v->amount * 100),
                            'sett_date' => $timeSett,  // 结算日期 也就是运行的日期
                            'type' => $v->type,
                            'time' => $v->act_time,   // 结算日期  佣金结算的日期 例如三月份佣金
                            'fail_id' => $field_id,
                            'express_num' => $orderAll->express_number,
                            'express_name' => $orderAll->express_company,
                            'status_desc' => $orderAll->status_desc,
                            'order_date' => $orderAll->created_at,
                            'goods_name' => $orderAll->goods_name,
                            'goods_code' => $orderAll->goods_code,
                            'ordersno' => $orderAll->ordersno,
                            'dist_ordersno' => $orderAll->dist_ordersno,
                            'iccid' => $orderAll->iccid,
                            'phone' => $orderAll->contact_phone
                        ];
                    }

                    // 处理代理
                    if (!empty($orderAll->shop_id_str) && !empty($orderAll->shop_name_str)) {
                        $resIdStr = explode('.', $orderAll->shop_id_str);
                        $resNameStr = explode('.', $orderAll->shop_name_str);
                        $dist_id = '';
                        $dist_name = '';
                        $sup_id = '';
                        $sup_name = '';
                        foreach ($resIdStr as $key => $va) {
                            if ($va == $v->shop_id) {
                                if (!empty($resNameStr[$key + 1])) {
                                    $dist_name = $resNameStr[$key + 1];
                                }
                                if (!empty($resIdStr[$key + 1])) {
                                    $dist_id = $resIdStr[$key + 1];
                                }
                                if (!empty($resNameStr[$key])) {
                                    $sup_name = $resNameStr[$key];
                                }
                                if (!empty($resIdStr[$key])) {
                                    $sup_id = $resIdStr[$key];
                                }
                                break;
                            }
                        }
                    }
                    if (!empty($dist_id)) {
                        $addData['shop_id'] = $dist_id;
                    }
                    if (!empty($dist_name)) {
                        $addData['shop_str'] = $dist_name;
                    }
                    if (!empty($sup_id)) {
                        $addData['sup_id'] = $sup_id;
                    }
                    if (!empty($sup_name)) {
                        $addData['sup_name'] = $sup_name;
                    }
                    if (empty($dist_id)) {
                        $flag = false;
                        $three_msg = '该单未查到代理';
                    }
                    $updateMid = [
                        'is_run' => 1,
                        'status' => 1
                    ];
                    if ($flag) {
                        $updateMid['status'] = 2;
                        // 直接插入就OK
                        $this->dataModel->insert($addData);
                    }
                    if (!$flag) {
                        $updateMid['remark'] = $three_msg;
                    }
                    $this->productModel->where(['id' => $v->id])->update($updateMid);
                }
            }
        }
        if (!empty($resData) && count($resData) < 50) {
            // 运行 count  生成的count数据
            dispatch(new Subpackage($field_id, 'createCountCommission', 5))->onQueue('TaskLongFileDispose');
        }
        if (!$resData || count($resData) >= 50) {
            dispatch(new Subpackage($field_id, 'createCommission'))->onQueue('TaskLongFileDispose');
        }
        return $this->returnMsg(200, '佣金运行完成');
    }
    // 运行失败的文件
    // 生成佣金的统计数据
    public function createCountCommission($id)
    {
        if (empty($id)) {
            return $this->returnMsg(100, '传递数据不正确');
        }
        $datas = DB::Table('order_commission')->where(['fail_id' => $id])->select(DB::raw('sum(amount) as amount,count(*) as nums,shop_id,shop_str,sup_id,sup_name,type,sett_date,time'))->groupBy('shop_id', 'shop_str', 'sup_id', 'sup_name', 'type', 'sett_date', 'time')->get();
        $coundModel = new OrderCommissionCountModel();
        $addData = [];
        $count_amount = 0;
        $shop_id = 0;
        if ($datas) {
            // 插入count数据中
            foreach ($datas as $key => $v) {
                $addData[] = [
                    'shop_id' => $v->shop_id,
                    'shop_str' => $v->shop_str,
                    'sup_id' => $v->sup_id,
                    'sup_name' => $v->sup_name,
                    'amount' => $v->amount,
                    'sett_date' => $v->sett_date,
                    'type' => $v->type,
                    'time' => $v->time,
                    'nums' => $v->nums,

                ];
                $shop_id = $v->sup_id;
                $count_amount += $v->amount;
            }
        }
        if (!empty($addData)) {
            $coundModel->insert($addData);
        }

        // 运行结束
        $update = [
            'is_run' => 2,
            'count_amount' => $count_amount,
        ];
        $model = new OrderCommissionFileRepository();
        $isUp = $model->edit(['id' => $id], $update);
        if ($isUp) {
            // 生成失败的文件
            return $this->createExcel($id, 1, $shop_id);
        }
        return $isUp;
    }

    // 生成文件
    public function createExcel($file_id, $type, $shop_id = 0, $dist_id = 0, $count_id = 0)
    {

        // 效验失败的生成
        if ($type == 1) {
            $where = [
                'more_file_id' => $file_id,
                'status' => 1
            ];
            $resData = DB::table('order_commission_midd')->where($where)->select(['dist_orderno', 'iccid', 'amount', 'three_msg', 'remark'])->get();
            $excelModel = new Excel();
            $title = [
                '订单号', '入网号码', '金额', '结清原因', '失败原因'
            ];
            $filename = '/attach/failFiel/' . $shop_id . '/' . date('Ymd') . '/' . rand(100000, 999999) . '.xlsx';
            $excelModel->exportFile($resData, $title, $filename);
            $update = [
                'fail_rout' => $filename,
            ];
            return DB::table('order_commission_file')->where(['id' => $file_id])->update($update);
        }

        // 代理的订单的数据生成
        if ($type == 2) {
            $where = [
                'fail_id' => $file_id,
                'shop_id' => $shop_id
            ];
            if (!empty($dist_id)) {
                $where['shop_id'] = $dist_id;
                $where['sup_id'] = $shop_id;
            }

            // var_dump($where);
            $resData = DB::table('order_commission')->where($where)->select(['ordersno', 'dist_ordersno', 'iccid', 'amount', 'goods_name', 'goods_code', 'type', 'sup_name', 'order_date', 'sett_date'])->get();
            $excelModel = new Excel();
            $title = [
                '订单号', '外部订单号', '入网号码', '金额(单位分)', '商品名称', '商品编码', '类型', '供应商名称', '下单日期', '结算日期'
            ];
            $filename = '/attach/failFiel/' . $shop_id . '/' . date('Ymd') . '/' . rand(100000, 999999) . '.xlsx';
            $excelModel->exportFile($resData, $title, $filename);
            $update = [
                'fail_rout' => $filename,
            ];
            $res = DB::table('order_commission_count')->where(['id' => $count_id])->update($update);
            if ($res) {
                return $this->returnMsg(200, '生成成功,请刷新下载');
            }
        }
        return $this->returnMsg(200, '生成excel文档失败');
    }
}
